package com.shushan.setting;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.fingerprintidentify.FingerprintIdentify;
import com.android.fingerprintidentify.base.BaseFingerprint;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.login.LoginOrRegisterActivity;
import com.shushan.network.UrlConst;
import com.shushan.pages.SetActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.UmengEventUtil;
import com.shushan.web.AdvertWebActivity;
import com.shushan.web.ProtocolWebActivity;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

/**
 * @ClassName: SettingActivity
 * @Desciption: //TODO
 * @author: yichaohua
 * @date: 2018-12-11
 */
public class SettingActivity extends NavigationLoseActivity implements View.OnClickListener, VerificationCodeView.OnCodeFinishListener {

    private static final String TAG = "SettingActivity";

    private RelativeLayout personInfoLayout;
    private RelativeLayout studyRewardLayout;
    private RelativeLayout parentPswLayout;
    private RelativeLayout versionInfoLayout;
    private RelativeLayout protocolLayout;
    private RelativeLayout reliefLayout;
    private RelativeLayout aboutUsLayout;
    private Button logoutButton;
    private Dialog parentPswDialog;
    private VerificationCodeView veriCodeView;
    private FingerprintIdentify mFingerprintIdentify;

    private BabyApplication shuShanApplication = BabyApplication.getInstance();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.setting_activity);

        setTitle("设置");

        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(parentPswDialog != null){
            parentPswDialog.dismiss();
        }

        if(mFingerprintIdentify != null){
            mFingerprintIdentify.cancelIdentify();
        }
    }

    private void initView() {
        personInfoLayout = findViewById(R.id.setting_person_info_layout);
        personInfoLayout.setOnClickListener(this);
        studyRewardLayout = findViewById(R.id.setting_study_reward_layout);
        studyRewardLayout.setOnClickListener(this);
        parentPswLayout = findViewById(R.id.setting_parent_psw_layout);
        parentPswLayout.setOnClickListener(this);
        versionInfoLayout = findViewById(R.id.setting_version_info_layout);
        versionInfoLayout.setOnClickListener(this);
        protocolLayout = findViewById(R.id.setting_protocol_layout);
        protocolLayout.setOnClickListener(this);
        reliefLayout = findViewById(R.id.setting_relief_layout);
        reliefLayout.setOnClickListener(this);
        aboutUsLayout = findViewById(R.id.setting_about_layout);
        aboutUsLayout.setOnClickListener(this);
        logoutButton = findViewById(R.id.setting_logout_btn);
        logoutButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.setting_person_info_layout:
                startActivity(ParentSettingActivity.class);
                break;
            case R.id.setting_study_reward_layout:
                startActivity(RewardSettingActivity.class);
                break;
            case R.id.setting_parent_psw_layout:
                Intent intent = new Intent(this,ParentPswSetActivity.class);
                intent.putExtra("isParentSet",true);
                startActivityAllow(intent);
                break;
            case R.id.setting_version_info_layout:
                startActivity(SetActivity.class);
                break;
            case R.id.setting_logout_btn:
                logout();
                break;
            case R.id.setting_protocol_layout:
                gotoProtocolWeb();
                break;
            case R.id.setting_relief_layout:
                UrlParse urlParse = new UrlParse(UrlConst.BASE_URL).appendRegion(UrlConst.RELIEF_HTML);
                Intent intent2 = new Intent(this, AdvertWebActivity.class);
                intent2.putExtra("url",urlParse.toString());
                startActivityAllow(intent2);
                break;
            case R.id.setting_about_layout:
                UrlParse urlParse1 = new UrlParse(UrlConst.BASE_URL).appendRegion(UrlConst.ABOUT_US_HTML);
                Intent intent3 = new Intent(this, AdvertWebActivity.class);
                intent3.putExtra("url",urlParse1.toString());
                startActivityAllow(intent3);
                break;
            default:
                break;
        }
    }

    @Override
    public void onComplete(String content) {
        if(StringTools.pswValide(content)){
            doLogout();
        }else {
            showToast("家长密码错误");
            if(veriCodeView != null){
                veriCodeView.clear();
            }
        }
    }

    private void doLogout(){
        final PushAgent mPushAgent = PushAgent.getInstance(this);
        int currentChildId = shuShanApplication.getCurrentChildId();
        if(currentChildId > 0){
            mPushAgent.deleteAlias(currentChildId+"", Constants.UMENG_ALIAS_CHILD_ID_KEY, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                }
            });
        }

        int useId = SharedPreferencesUtils.getIntDate(Constants.CURRENT_USE_ID_SHAREPREFERS_KEY);
        if(useId > 0){
            mPushAgent.deleteAlias(useId+"", Constants.UMENG_ALIAS_USE_ID_KEY, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                }
            });
        }

        UmengEventUtil.onProfileSignOff();

        Intent intent = new Intent(this,LoginOrRegisterActivity.class);
        intent.putExtra("isLogout",true);
        startActivityAllow(intent);

        onBackAction();
        SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,false);
    }

    private void logout() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(!isChildControl || TextUtils.isEmpty(SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY))){
            showLogoutDialog();
            return;
        }

        showParentPswDialog();
    }

    private void showLogoutDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("您是否确认退出登录？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        doLogout();
                    }
                })
                .create().show();
    }

    private void showParentPswDialog() {
        if(parentPswDialog == null){
            parentPswDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
            parentPswDialog.setContentView(R.layout.change_to_parent_dialog);
            parentPswDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

            veriCodeView = parentPswDialog.findViewById(R.id.verification_code_view);
            veriCodeView.setOnCodeFinishListener(this);
            Button coloseButton = parentPswDialog.findViewById(R.id.btn_cancel);
            coloseButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    parentPswDialog.dismiss();
                    if(mFingerprintIdentify != null){
                        mFingerprintIdentify.cancelIdentify();
                    }
                }
            });

            parentPswDialog.setCancelable(false);
        }

        if(mFingerprintIdentify == null){
            mFingerprintIdentify = new FingerprintIdentify(BabyApplication.getInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG,exception.getLocalizedMessage());
                }
            });
        }

        ImageView parentImg = parentPswDialog.findViewById(R.id.parent_psw_img);
        ImageView fingerIconImg = parentPswDialog.findViewById(R.id.parent_finger_icon_img);
        final TextView hintText = parentPswDialog.findViewById(R.id.parent_dialog_hint_tv);
        hintText.setVisibility(View.GONE);
        if(mFingerprintIdentify.isFingerprintEnable()
                && mFingerprintIdentify.isHardwareEnable()
                && mFingerprintIdentify.isRegisteredFingerprint()){

            parentImg.setVisibility(View.GONE);
            fingerIconImg.setVisibility(View.VISIBLE);

            ((TextView)parentPswDialog.findViewById(R.id.parent_dialog_tv)).setText("请验证指纹或者家长密码退出登录");

            mFingerprintIdentify.startIdentify(5, new BaseFingerprint.FingerprintIdentifyListener() {
                @Override
                public void onSucceed() {
                    doLogout();
                    parentPswDialog.dismiss();
                }

                @Override
                public void onNotMatch(int availableTimes) {
                    hintText.setVisibility(View.VISIBLE);
                    hintText.setText("指纹不匹配，还剩余" + availableTimes + "次机会");
                    Animation shake = AnimationUtils.loadAnimation(SettingActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);

                }

                @Override
                public void onFailed(boolean isDeviceLocked) {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(SettingActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onStartFailedByDeviceLocked() {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(SettingActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }
            });
        }else {
            parentImg.setVisibility(View.VISIBLE);
            fingerIconImg.setVisibility(View.GONE);
            ((TextView)parentPswDialog.findViewById(R.id.parent_dialog_tv)).setText("请输入家长密码退出登录");
        }

        if(veriCodeView != null){
            veriCodeView.clear();
        }

        if(!parentPswDialog.isShowing()){
            parentPswDialog.show();
        }
    }

    private void gotoProtocolWeb(){
        UrlParse urlParse = new UrlParse(UrlConst.BASE_URL)
                .appendRegion(UrlConst.USER_PROTOCOL);

        Intent intent = new Intent(this, ProtocolWebActivity.class);
        intent.putExtra("title","用户协议");
        intent.putExtra("url",urlParse.toString());
        startActivityAllow(intent);
    }
}
